package com.example.demoforstudentsystem;

import java.util.ArrayList;
import java.util.List;

import android.R.array;
import android.R.bool;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class StudentDAO {
	private StudentHelper studentHelper;
	
	public StudentDAO(Context context) {
		studentHelper=new StudentHelper(context);
	}

	public void add(String name,String number,String sex) {
		SQLiteDatabase sqLiteDatabase=studentHelper.getWritableDatabase();
		sqLiteDatabase.execSQL("insert into students (name,number,sex) values (?,?,?)", new Object[]{name,number,sex});
		sqLiteDatabase.close();
	}
	public void del(String name) {
		SQLiteDatabase sqLiteDatabase=studentHelper.getWritableDatabase();
		sqLiteDatabase.execSQL("delete from students where name=?",new Object[]{name});
		sqLiteDatabase.close();
	}
	public void update(String name,String number,String sex){
		SQLiteDatabase sqLiteDatabase=studentHelper.getWritableDatabase();
		sqLiteDatabase.execSQL("update students set number =?,sex=? where name =?",new Object[]{number,sex,name});
		sqLiteDatabase.close();
	}
	public boolean find(String name){
		String sex="";	
		String number="";
		SQLiteDatabase sqLiteDatabase=studentHelper.getWritableDatabase();
		Cursor cursor=sqLiteDatabase.rawQuery("select number,sex from students where name=?", new String[]{name});
		boolean result=cursor.moveToNext();
		boolean find_result=false;
		if(result){
//			number=cursor.getString(0);
//			sex=cursor.getString(1);
			find_result=true;
		}				
		cursor.close();
		sqLiteDatabase.close();
		return find_result;
	}
	public String find_a(String name){
		String sex="";	
		String number="";
		SQLiteDatabase sqLiteDatabase=studentHelper.getWritableDatabase();
		Cursor cursor=sqLiteDatabase.rawQuery("select number,sex from students where name=?", new String[]{name});
		boolean result=cursor.moveToNext();
		boolean find_result=false;
		if(result){
			number=cursor.getString(0);
			sex=cursor.getString(1);
			
		}				
		cursor.close();
		sqLiteDatabase.close();
		
		return number+","+sex;
	}
	public List<Student> find_all(){
		List<Student> students=new ArrayList<Student>();
		SQLiteDatabase sqLiteDatabase=studentHelper.getWritableDatabase();
		Cursor cursor=sqLiteDatabase.rawQuery("select name,number,sex from students",null);
		boolean result=cursor.moveToNext();
		String number="";
		String name="";
		String sex="";
		while(result){
			name=cursor.getString(0);
			number=cursor.getString(1);
			sex=cursor.getString(2);
			Student student=new Student();
			student.setName(name);
			student.setNumber(number);
			student.setSex(sex);
			students.add(student);
		}
		cursor.close();
		sqLiteDatabase.close();
		return students;
	}
	
}
